import {dropState, fetchState, setDone} from './state.js';
import {defineTimeToLeftBadgeString} from "./common.js";

let interval = null;

function resetInterval(){
    if (interval != null) {
        clearInterval(interval);
    }
    interval = setInterval(updateTimeBar, 200);
}

function updateTimeBar() {
    fetchState()
        .then(async state => {
            let now = new Date();
            let diff = state.countTo - now.getTime();
            if(diff > 0){
                let str = defineTimeToLeftBadgeString(state);
                chrome.action.setBadgeText({text: str});
            }else{

                if(!state.done){
                    state = await setDone()
                }
            }
            if(!interval){
                interval = setInterval(updateTimeBar, 200);
            }
        // setTimeout(updateTimeBar, 1000);
    })
}



chrome.runtime.onInstalled.addListener(() => {
    console.log('Extension installed');
    dropState().then();
    // Prepare some data or respond to events
});

// Example of sending a message to the popup
function updatePopup() {
    chrome.runtime.sendMessage({action: "update", data: "New data from background"});
}
function updateData() {
    chrome.storage.local.set({key: "value"}, (value)=> {
        console.log("Value is set to " + value);
    });
}

// chrome.runtime.onInstalled.addListener(async (details) => {
//     console.log('Extension installed');
//     if (details.reason === chrome.runtime.OnInstalledReason.INSTALL) {
//         chrome.tabs.create({ url: "https://harbor.cards/timer-countdown" });
//     }
//     chrome.runtime.setUninstallURL('https://forms.gle/uga9ZbF454Gire6S9', () => {
//         if (chrome.runtime.lastError) {
//             console.error('Error setting uninstall URL:', chrome.runtime.lastError);
//         } else {
//             console.log('Uninstall URL set successfully.');
//         }
//     });
// });

chrome.runtime.onStartup.addListener(async() => {
    console.log("Browser started, service worker is awake");
    updateTimeBar();
});

// For long-lived connections:
chrome.runtime.onConnectExternal.addListener(function(port) {
    port.onMessage.addListener(function(msg) {
        // See other examples for sample onMessage handlers.
    });
});


chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message === "activate") {
        console.log("background.js activated", event);
        updateTimeBar();
    }
    return true;
});
// updatePopup();
// updateData();
updateTimeBar();
